package org.lovo.util;

import net.coobird.thumbnailator.Thumbnails;
import org.lovo.vo.FileVo;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class UploadFile {
    /**
     * 上传文件返回文件地址
     * @param tag 0-压缩 1-不压缩
     * @return
     */
    public static FileVo upload(MultipartFile file,int tag) throws IOException {
        FileVo vo=new FileVo();
        vo.setCode(500);
        if(null!=file) {
           boolean bl=false;
            String fileName = file.getOriginalFilename();
            if (StringUtil.StringVerify(fileName)) {
                int num=  fileName.lastIndexOf(".");
                String imgStr=fileName.substring(num,fileName.length());
                    //验证格式
                   for(String format:StringUtil.UPLOAD_FORMAT){
                            if(file.getContentType().equals(format)){
                                bl=true;
                                break;
                            }
                   }
                 if(bl) {
                     File f = new File(StringUtil.IMG_PATH);
                     if (!f.exists()) {
                         f.mkdirs();
                     }
                     //给文件重命名
                     File tempFile = new File(StringUtil.IMG_PATH + SnowIdUtils.uniqueLong() + imgStr);

                     BufferedImage image = ImageIO.read(file.getInputStream());
                     if(tag==0) {
                         //压缩图片
                         Thumbnails.of(image).size(1024, 800).outputQuality(1f).toFile(tempFile);
                     }else {
                         file.transferTo(tempFile);
                     }
                     vo.setImgPath(SnowIdUtils.uniqueLong() + imgStr);
                     vo.setCode(200);
                }
            }
        }

        return vo;
    }
}
